<template>
  <div class="recorder">
    <button @click="startRecording" :disabled="isRecording">开始录音</button>
    <button @click="stopRecording" :disabled="!isRecording">停止录音</button>
    <button @click="playRecording" :disabled="!audioUrl">播放录音</button>

    <audio ref="audioPlayer" controls v-if="audioUrl" :src="audioUrl"></audio>
  </div>
</template>

<script>
export default {
  name: 'Recorder',
  data() {
    return {
      mediaRecorder: null,
      audioChunks: [],
      audioUrl: null,
      isRecording: false
    }
  },
  methods: {
    async startRecording() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
        this.mediaRecorder = new MediaRecorder(stream)
        this.audioChunks = []

        this.mediaRecorder.ondataavailable = event => {
          if (event.data.size > 0) {
            this.audioChunks.push(event.data)
          }
        }

        this.mediaRecorder.onstop = () => {
          const blob = new Blob(this.audioChunks, { type: 'audio/webm' })
          this.audioUrl = URL.createObjectURL(blob)
        }

        this.mediaRecorder.start()
        this.isRecording = true
        console.log('开始录音...')
      } catch (error) {
        console.error('无法访问麦克风：', error)
      }
    },

    stopRecording() {
      if (this.mediaRecorder && this.isRecording) {
        this.mediaRecorder.stop()
        this.isRecording = false
        console.log('录音已停止')
      }
    },

    playRecording() {
      if (this.audioUrl) {
        const audio = this.$refs.audioPlayer
        audio.play()
      }
    }
  }
}
</script>

<style scoped>
.recorder {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

button {
  padding: 8px 12px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  background-color: #409eff;
  color: white;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>
